﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using Infragistics.Win.UltraWinGrid;

namespace DMSClient.General
{
    public partial class Scheduler : Form
    {
        EndpointAddress address;
        DataSet ds;
        DataTable dtPeriodos;
        DataTable dtGrupos;
        DataTable dtSchedule;
        UltraDropDown uddPeriods;
        UltraDropDown uddEmailGroups;
        WSHttpBinding Binding = new WSHttpBinding();
        string ambiente;
        
        public Scheduler()
        {
            InitializeComponent();
            ambiente = Properties.Settings.Default.CurrentEnv;
            Binding.MaxReceivedMessageSize = 2147483647;
            Binding.MaxBufferPoolSize = 2147483647;
            Binding.ReceiveTimeout = TimeSpan.MaxValue;
            Binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
            Binding.Security.Mode = SecurityMode.None;
            address = new EndpointAddress(Properties.Settings.Default.Server);

            this.Text = Properties.Settings.Default.CurrentEnvDes + " - Schedule";
        }

        private void Scheduler_Load(object sender, EventArgs e)
        {
             
            WorkerSchedule.RunWorkerAsync();
            estado(false);
          //  BindUltraDropDown();
        }


        #region GET SCHEDULE
        private void WorkerSchedule_DoWork(object sender, DoWorkEventArgs e)
        {
            DMSServices.DMSServicesClient client;
            client = new DMSServices.DMSServicesClient(Binding, address);
            string periods = null;
            string groups = null;
            string schedule = null;
            string distributor = null;
            try
            {
                client.Open();
                    periods = client.getPeriodSchedule();
                    groups = client.getEmailGroups();
                    schedule = client.getPeriodScheduleAlerts();               
                client.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, ex.InnerException);
            }
            if (groups == null)
            {
                throw new Exception(Properties.Settings.Default.DistributorsNullListErrorMsg);
            }

            // PERIODOS
            dtPeriodos = new DataTable("dtPeriodSchedule");
            dtPeriodos.Columns.Add("idPeriodSchedule");
            dtPeriodos.Columns.Add("dsPeriodSchedule");
            dtPeriodos.Columns.Add("MinutesPeriodSchule");

            //GRUPOS
            dtGrupos = new DataTable("dtEmailGroups");
            dtGrupos.Columns.Add("IdEmailGroup");
            dtGrupos.Columns.Add("DsName");

            //SCHEDULE
            dtSchedule = new DataTable("dtScheduleAlerts");
            dtSchedule.Columns.Add("idSchedule");
            dtSchedule.Columns.Add("NextTimeSchedule");
            dtSchedule.Columns.Add("LastTimeExecSchedule");
            dtSchedule.Columns.Add("IntervalSchedule");
            dtSchedule.Columns.Add("periodSchedule");
            dtSchedule.Columns.Add("idEmailGroup");            

            ds = new DataSet();
            ds.Tables.Add(dtPeriodos);
            ds.Tables.Add(dtGrupos);
            ds.Tables.Add(dtSchedule);

            System.IO.StringReader xmlSR = new System.IO.StringReader(periods);
            ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();

            System.IO.StringReader xmlSR1 = new System.IO.StringReader(groups);
            ds.ReadXml(xmlSR1, XmlReadMode.ReadSchema);
            xmlSR1.Close();

            System.IO.StringReader xmlSR2 = new System.IO.StringReader(schedule);
            ds.ReadXml(xmlSR2, XmlReadMode.ReadSchema);
            xmlSR2.Close();

        }

        private void WorkerSchedule_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    estado(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                BindUltraDropDown();
                ugSchedule.DataSource = ds.Tables[2];
                ugSchedule.DisplayLayout.Bands[0].Columns["periodSchedule"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDownValidate;
               // ugSchedule.DisplayLayout.Bands[0].Columns["idEmailGroup"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDown;
                ugSchedule.DisplayLayout.Bands[0].Columns["NextTimeSchedule"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DateTime;
                ugSchedule.DisplayLayout.Bands[0].Columns["IntervalSchedule"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.Integer;
                ugSchedule.DisplayLayout.Bands[0].Columns["IntervalSchedule"].MaskInput = "nnnn";
                ugSchedule.DisplayLayout.Bands[0].Columns["idSchedule"].Hidden = true;
                ugSchedule.DisplayLayout.Bands[0].Columns["periodSchedule"].Width = 150;
                ugSchedule.DisplayLayout.Bands[0].Columns["idEmailGroup"].Width = 250;
                ugSchedule.DisplayLayout.Bands[0].Columns["idEmailGroup"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDownValidate; 
                ugSchedule.DisplayLayout.Bands[0].Columns["NextTimeSchedule"].Width = 150;
               // ugSchedule.DisplayLayout.Bands[0].Columns["LastTimeExecSchedule"].CellActivation = Activation.Disabled;
                ugSchedule.DisplayLayout.Bands[0].Columns["LastTimeExecSchedule"].CellActivation = Activation.NoEdit;
                
                if (ds.Tables[2].Rows.Count != 0) 
                {
                    ubDeleteSchedule.Visible = true;
                }
                else
                {
                    ubDeleteSchedule.Visible = false;
                }
                estado(true);

            }
        }
        #endregion
        public void estado(bool estado)
        {

            ugSchedule.Enabled = estado;             
            loader.Visible = !estado;

        }

        private void ugSchedule_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            foreach (UltraGridBand bands in e.Layout.Bands)
            {
                foreach (UltraGridColumn ugc in bands.Columns)
                {
                    ugc.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
                }
            }
            e.Layout.Bands[0].Columns["idEmailGroup"].ValueList = this.uddEmailGroups;
            e.Layout.Bands[0].Columns["periodSchedule"].ValueList = this.uddPeriods;
        }
        private void BindUltraDropDown()
        {
            try
            {
                
                uddPeriods = new UltraDropDown();
                uddPeriods.SetDataBinding(ds.Tables[0], null);
                uddPeriods.ValueMember = "idPeriodSchedule";
                uddPeriods.DisplayMember = "dsPeriodSchedule";
                

                uddEmailGroups = new UltraDropDown();
                //uddEmailGroups.DisplayLayout.e
                uddEmailGroups.SetDataBinding(dtGrupos, null);
                uddEmailGroups.ValueMember = "IdEmailGroup";
                uddEmailGroups.DisplayMember = "DsName";
                uddEmailGroups.DisplayLayout.Bands[0].Columns["IdEmailGroup"].Hidden = true;
                uddEmailGroups.DisplayLayout.Bands[0].Columns["DsName"].Width = 250;
                

            }
            catch (Exception ex) { }
        }

        

        private void ubAdd_Click(object sender, EventArgs e)
        {
            int count = 0;
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugSchedule.Rows)
            {

                if (!validateSchedule(row))
                {
                    count++;
                }
            }
            if (count == 0)
            {
                ugSchedule.Rows.Band.AddNew();  
            }
             
        }

        #region SAVE SCHEDULE
        private void ubSave_Click(object sender, EventArgs e)
        {
            bool sw  = false;
             
             
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugSchedule.Rows)
            {
                if (row != null)
                {
                    if (validateSchedule(row))
                    {
                        sw = true;
                    }
                    else
                    {
                        sw = false;
                    }
                }

            }

            if (sw)
            {
                estado(false);
                WorkerSave.RunWorkerAsync();
            }

        }

        private void WorkerSave_DoWork(object sender, DoWorkEventArgs e)
        {
            DMSServices.DMSServicesClient client;
            client = new DMSServices.DMSServicesClient(Binding, address);

            List<Dtl.Schedule> listSchedule = new List<Dtl.Schedule>();
            

            //GUARDO EN LA LISTA DE GRUPOS
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugSchedule.Rows)
            {
                 
                if (row != null)
                {
                    Dtl.Schedule Schedule = new Dtl.Schedule();
                    Schedule.NextTimeSchedule = DateTime.Parse(row.Cells["NextTimeSchedule"].Value.ToString());
                    Schedule.LastTimeExecSchedule = DateTime.Parse(row.Cells["LastTimeExecSchedule"].Value.ToString());
                    Schedule.IntervalSchedule = int.Parse(row.Cells["IntervalSchedule"].Value.ToString());
                    Schedule.periodSchedule = int.Parse(row.Cells["periodSchedule"].Value.ToString());
                    Schedule.idEmailGroup = int.Parse(row.Cells["idEmailGroup"].Value.ToString());

                    if (row.Cells["idSchedule"].Value.ToString().Equals(""))
                    {
                        Schedule.typeOperation = true;
                    }
                    else
                    {
                        Schedule.typeOperation = false;
                        Schedule.idScheduler = int.Parse(row.Cells["idSchedule"].Value.ToString());
                    }

                    listSchedule.Add(Schedule);


                }

            }
            try
            {
                client.Open();
                int resul = client.setScheduleAlerts(listSchedule);
                if (resul == 1)
                {
                    MessageBox.Show("Successfully saved record!", "Schedule Alerts");

                }
                else
                {
                    MessageBox.Show("Error saving the record, please try again!", "Schedule Alerts");
                }
                client.Close();
                if (WorkerSave.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex.InnerException);
            }
            
        }

        private void WorkerSave_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    estado(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                estado(true);
                WorkerSchedule.RunWorkerAsync();
            }
        }
        #endregion

        #region VALIDATE SCHEDULE
        private bool validateSchedule(UltraGridRow row) 
        {
            if (row.Cells["NextTimeSchedule"].Value.ToString().Equals(""))
            {
                MessageBox.Show("Please choose field NextTimeSchedule", "Schedule");
                return false;
            }
            if (row.Cells["IntervalSchedule"].Value.ToString().Equals(""))
            {
                MessageBox.Show("Please choose field IntervalSchedule", "Schedule");
                return false;
            }
            if (!IsNum(row.Cells["IntervalSchedule"].Value.ToString()))
            {
                MessageBox.Show("The IntervalSchedule field must be in mumeric format", "Schedule");
                return false;
            }
            if (row.Cells["periodSchedule"].Value.ToString().Equals(""))
            {
                MessageBox.Show("Please choose field periodSchedule", "Schedule");
                return false;
            }
            
            if (row.Cells["idEmailGroup"].Value.ToString().Equals(""))
            {
                MessageBox.Show("Please choose field idEmailGroup", "Schedule");
                return false;
            }
           

            return true;

        }

        public static bool IsNum(string inValue)
        {
            bool result;
            try
            {
                int myDT = int.Parse(inValue);
                result = true;
            }
            catch (FormatException e)
            {
                result = false;
            }

            return result;
        }
        #endregion

        #region DELETE SCHEDULE
        private void ubDeleteSchedule_Click(object sender, EventArgs e)
        {

            bool FILA = false;
            string id = "";
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugSchedule.Rows)
            {
                if (row.IsActiveRow)
                {
                    FILA = true;
                    id = row.Cells["idEmailGroup"].Text;
                }
            }
            if (FILA)
            {
                MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                string caption = "SCHEDULE";
                string mensaje = "Do You're  sure that want to delete the schedule '" + id + "'?";
                DialogResult resultado = MessageBox.Show(mensaje, caption, buttons);


                if (resultado == DialogResult.Yes)
                {
                    estado(false);
                    WorkerDelete.RunWorkerAsync();
                }
            }
            else
            {

                MessageBox.Show("Please, choose you a row of Schedule to deleted!", "FTP");
            }
        }
       

        private void WorkerDelete_DoWork(object sender, DoWorkEventArgs e)
        {
            DMSServices.DMSServicesClient client;
            client = new DMSServices.DMSServicesClient(Binding, address);
            int IdSchedule = -1;
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugSchedule.Rows)
            {
                if (row.IsActiveRow)
                {
                    IdSchedule = int.Parse(row.Cells["idSchedule"].Value.ToString());
                    break;
                }
            }


            if (IdSchedule != -1)
            {
                try
                {
                    client.Open();
                    if (client.DeleteSchedule(IdSchedule) == 1)
                    {
                        MessageBox.Show("Successfully deleted record!", "SCHEDULE");

                    }
                    else
                    {
                        MessageBox.Show("Error deleted the record, please try again!", "SCHEDULE");
                    }
                    client.Close();
                    if (WorkerDelete.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message, ex.InnerException);
                }

            }
            else
            {
                MessageBox.Show("Error deleted the record, please try again!", "SCHEDULE");
            }
        }

        private void WorkerDelete_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    estado(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                estado(true);
                WorkerSchedule.RunWorkerAsync();
            }

        }
        #endregion

        private void ugSchedule_CellChange(object sender, CellEventArgs e)
        {

           
        }

        private void ugSchedule_BeforeCellUpdate(object sender, BeforeCellUpdateEventArgs e)
        {
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugSchedule.Rows)
            {

                if (row.IsActiveRow && e.Cell.Equals("NextTimeSchedule") && row.Cells["idSchedule"].Value.ToString().Equals(""))
                {
                    row.Cells["LastTimeExecSchedule"].Value = row.Cells["NextTimeSchedule"].Value;
                }
            }
        }

         
         

        

        private void ugSchedule_AfterCellUpdate(object sender, CellEventArgs e)
        {
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugSchedule.Rows)
            {

                if (e.Cell.Equals("NextTimeSchedule") && row.Cells["idSchedule"].Value.ToString().Equals(""))
                {
                    row.Cells["LastTimeExecSchedule"].Value = row.Cells["NextTimeSchedule"].Value;
                }
            }
        }

        private void ugSchedule_AfterCellActivate(object sender, EventArgs e)
        {
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugSchedule.Rows)
            {

                if ( row.Cells["idSchedule"].Value.ToString().Equals(""))
                {
                    row.Cells["LastTimeExecSchedule"].Value = row.Cells["NextTimeSchedule"].Value;
                }
            }
        }

        private void Scheduler_Resize(object sender, EventArgs e)
        {
            loader.Left = (this.Width - loader.Width) / 2;
            loader.Top = ((this.Height - loader.Height) / 2) - loader.Height;
        }

        private void Scheduler_Shown(object sender, EventArgs e)
        {
            loader.Left = (this.Width - loader.Width) / 2;
            loader.Top = ((this.Height - loader.Height) / 2) - loader.Height;
        }

        private void ugSchedule_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(127))
            {
                ubDeleteSchedule_Click(sender,e);
            }
        }

        private void ugSchedule_KeyDown(object sender, KeyEventArgs e)            
        {
           /* KeyPressEventArgs evento ;
            if (e.KeyChar == Convert.ToChar(127))
            {
                ubDeleteSchedule_Click(sender, e);
            }*/
        }

        private void ugSchedule_AfterRowActivate(object sender, EventArgs e)
        {
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugSchedule.Rows)
            {
                if (row.IsActiveRow)
                {
                    if (row.Cells["idSchedule"].Value.ToString().Equals(""))
                    {
                        ubDeleteSchedule.Visible = false;
                    }
                    else
                    {
                        ubDeleteSchedule.Visible = true;
                    }
                }
            }
        }

        private void ugSchedule_AfterSelectChange(object sender, AfterSelectChangeEventArgs e)
        {
            foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in ugSchedule.Rows)
            {
                if (row.IsActiveRow)
                {
                    if (row.Cells["idSchedule"].Value.ToString().Equals(""))
                    {
                        ubDeleteSchedule.Visible = false;
                    }
                    else
                    {
                        ubDeleteSchedule.Visible = true;
                    }
                }
            }
        }

        private void ubCancel_Click(object sender, EventArgs e)
        {
            WorkerSchedule.RunWorkerAsync();
            estado(false);
        }

    }
}
